<template>
  <el-button type="primary" @click="add">添加用户</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>
  <el-table
    :data="userList"
    row-key="id"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="60">
      <!-- <template #default="scope">{{ scope.row.date }}</template> -->
    </el-table-column>
    <el-table-column property="loginAct" label="账号" width="120" />
    <el-table-column
      property="name"
      width="150"
      label="姓名"
      show-overflow-tooltip
    />
    <el-table-column
      property="phone"
      width="170"
      label="手机"
      show-overflow-tooltip
    />
    <el-table-column property="email" label="邮箱" show-overflow-tooltip="" />
    <el-table-column
      property="createTime"
      label="创键时间"
      show-overflow-tooltip
    />
    <el-table-column label="操作">
      <template #default="scope">
        <!-- 插槽 拿到当前行数据  scope.row相当于userList的user-->
        <el-button
          type="primary"
          @click="view(scope.row.id)"
          v-hasPermission="'user:view'"
          >详情</el-button
        >
        <el-button
          type="success"
          @click="edit(scope.row.id)"
          v-hasPermission="'user:edit'"
          >编辑</el-button
        >
        <el-button
          type="danger"
          @click="del(scope.row.id)"
          v-hasPermission="'user:delete'"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    background
    layout="prev, pager, next"
    :total="total"
    :page-size="pageSize"
    @prev-click="toPage"
    @next-click="toPage"
    @current-change="toPage"
  />

  <!-- 新增用户的弹窗 -->
  <el-dialog
    v-model="userDialogVisible"
    :title="userQuey.id > 0 ? '编辑用户' : '新增用户'"
    width="55%"
    center
    draggable
  >
    <el-form
      ref="userForm"
      :model="userQuey"
      label-width="105px"
      :rules="userRules"
    >
      <el-form-item label="账号" prop="loginAct">
        <el-input v-model="userQuey.loginAct" />
      </el-form-item>

      <el-form-item label="密码" v-if="userQuey.id > 0"
        ><!-- 编辑 -->
        <el-input type="password" v-model="userQuey.loginPwd" />
      </el-form-item>
      <el-form-item label="密码" prop="loginPwd" v-else
        ><!-- 编辑 -->
        <el-input type="password" v-model="userQuey.loginPwd" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="userQuey.name" />
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="userQuey.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userQuey.email" />
      </el-form-item>
      <el-form-item label="账号未过期" prop="accountNoExpired">
        <el-select v-model="userQuey.accountNoExpired" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="密码未过期" prop="credentialsNoExpired">
        <el-select v-model="userQuey.credentialsNoExpired" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账号未锁定" prop="accountNoLocked">
        <el-select v-model="userQuey.accountNoLocked" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账号启用" prop="accountEnabled">
        <el-select v-model="userQuey.accountEnabled" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="userSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { doDelete, doGet, doPost, doPut } from "@/http/httpRequest";
import router from "@/router/router";
import { messageTip, messageConfirm } from "@/util/util";
import { onMounted, reactive, ref, getCurrentInstance } from "vue";
export default {
  props: ["reload"],
  setup(props) {
    let userDialogVisible = ref(false);
    let userList = reactive([{}]);
    let pageSize = ref(0);
    let total = ref(0);
    let userQuey = reactive({});
    const { proxy } = getCurrentInstance();
    let userIdArray = ref([]);
    let userRules = {
      loginAct: [
        { required: true, message: "请输入登录账号", trigger: "blur" },
      ],
      loginPwd: [
        { required: true, message: "请输入登录密码", trigger: "blur" },
        { min: 6, max: 16, message: "登录密码长度为6-16位", trigger: "blur" },
      ],
      name: [
        { required: true, message: "请输入姓名", trigger: "blur" },
        {
          pattern: /^[\u4E00-\u9FA5]{1,5}$/,
          message: "姓名必须是中文",
          trigger: "blur",
        },
      ],
      phone: [
        { required: true, message: "请输入手机号码", trigger: "blur" },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "手机号码格式有误",
          trigger: "blur",
        },
      ],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        {
          pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
          message: "邮箱格式有误",
          trigger: "blur",
        },
      ],
      accountNoExpired: [
        { required: true, message: "请选择账号是否未过期", trigger: "blur" },
      ],
      credentialsNoExpired: [
        { required: true, message: "请选择密码是否未过期", trigger: "blur" },
      ],
      accountNoLocked: [
        {
          required: true,
          message: "请选择账号是否未未锁定",
          trigger: "blur",
        },
      ],
      accountEnabled: [
        { required: true, message: "请选择账号是否可用", trigger: "blur" },
      ],
    };
    onMounted(() => {
      getData();
    });
    function getData(current) {
      doGet("/api/users", { current: current }).then((resp) => {
        if (resp.data.code === 200) {
          Object.assign(userList, resp.data.data.list);
          userList.length = resp.data.data.list.length;
          pageSize.value = resp.data.data.pageSize;
          total.value = resp.data.data.total;
        }
      });
    }

    //current是element组件传过来的
    function toPage(current) {
      getData(current);
    }
    function view(id) {
      //路由跳转
      router.push("/dashboard/user/" + id);
    }
    function add() {
      const emptyUser = {
        id: 0,
        loginAct: "",
        loginPwd: "",
        name: "",
        phone: "",
        email: "",
        accountNoExpired: "",
        credentialsNoExpired: "",
        accountNoLocked: "",
        accountEnabled: "",
      };
      Object.assign(userQuey, emptyUser);
      userDialogVisible.value = true;
    }
    function userSubmit() {
      let formData = new FormData();
      for (let field in userQuey) {
        formData.append(field, userQuey[field]);
      }
      proxy.$refs.userForm.validate((isValid) => {
        if (isValid) {
          if (userQuey.id > 0) {
            doPut("/api/user", formData).then((resp) => {
              if (resp.data.code === 200) {
                messageTip("编辑成功", "success");
                props.reload();
              } else {
                messageTip("编辑失败", "fail");
              }
            });
          } else {
            doPost("/api/user", formData).then((resp) => {
              if (resp.data.code === 200) {
                messageTip("提交成功", "success");
                props.reload();
              } else {
                messageTip("提交失败", "fail");
              }
            });
          }
        }
      });
    }
    function edit(id) {
      userDialogVisible.value = true;
      loadUser(id);
    }
    function loadUser(id) {
      doGet("/api/user/" + id, {}).then((resp) => {
        if (resp.data.code === 200) {
          Object.assign(userQuey, resp.data.data);
          const noPassword = { loginPwd: "" };
          Object.assign(userQuey, noPassword);
        }
      });
    }
    let options = [
      { label: "是", value: 1 },
      { label: "否", value: 0 },
    ];
    function del(id) {
      messageConfirm("你确定要删除?")
        .then(() => {
          doDelete("/api/user/" + id, {}).then((resp) => {
            if (resp.data.code === 200) {
              messageTip("删除成功", "success");
              props.reload();
            } else {
              console.log(resp.data);
              messageTip("删除失败,原因：" + resp.data.msg, "error");
            }
          });
        })
        .catch(() => {
          messageTip("取消删除", "warning");
        });
    }
    function batchDel() {
      if (userIdArray.value.length < 0) {
        messageTip("请选择要删除的数据", "warning");
        return;
      }
      messageConfirm("你确定要删除?")
        .then(() => {
          let ids = userIdArray.value.join(",");
          doDelete("/api/user", { ids: ids }).then((resp) => {
            if (resp.data.code === 200) {
              messageTip("批量删除成功", "success");
              props.reload();
            } else {
              console.log(resp.data);
              messageTip("批量删除失败,原因：" + resp.data.msg, "error");
            }
          });
        })
        .catch(() => {
          messageTip("取消批量删除", "warning");
        });
    }

    //勾选或者取消勾选，触发该函数（已经勾选的数据自动依赖注入给我们这个函数的参数）
    function handleSelectionChange(selectionDataArray) {
      userIdArray.value = [];
      selectionDataArray.forEach((data) => {
        userIdArray.value.push(data.id);
      });
    }
    return {
      batchDel,
      handleSelectionChange,
      del,
      options,
      userList,
      getData,
      pageSize,
      total,
      toPage,
      view,
      userDialogVisible,
      add,
      userQuey,
      userRules,
      userSubmit,
      edit,
    };
  },
};
</script>
<style>
.el-pagination {
  margin-top: 12px;
}
.el-table {
  margin-top: 20px;
}
</style>